layui.config({
    base : "js/"
}).use(['form','layer','jquery','layedit','laydate'],function(){
    var form = layui.form(),
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        $ = layui.jquery;

    form.on('select(area)', function(data){
        var area_id=$('#area').val();
        $.ajax({
            type: 'POST',
            url: '/admin/room/getbuilding',
            data:{
                '_token':$('input[name=_token]').val(),
                'area_id':area_id
            },
            dataType:  'json',
            success: function(data){
                $("#building").html("<option value=''>请选择建筑</option>");
                if(data){
                    $.each(data, function(key, val) {
                        var option = $("<option>").val(val.id).text(val.name);
                        $("#building").append(option);
                    });
                }
                form.render('select');
                $("#building").get(0).selectedIndex=0;
            }
        });
    });

    form.on('select(building)', function(data){
        var building_id=$('#building').val();
        $.ajax({
            type: 'POST',
            url: '/admin/smoke/getroom',
            data:{
                '_token':$('input[name=_token]').val(),
                'building_id':building_id
            },
            dataType:  'json',
            success: function(data){
                $("#room").html("<option value=''>请选择房间</option>");
                if(data){
                    $.each(data, function(key, val) {
                        var option = $("<option>").val(val.id).text(val.name);
                        $("#room").append(option);
                    });
                }
                form.render('select');
                $("#room").get(0).selectedIndex=0;
            }
        });
    });

    form.on("submit(add)",function(data){
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        $.ajax({
            type:'post',
            url:'/nb/common/nbbind/store',
            async:false,
            data:{
                '_token':$('input[name=_token]').val(),
                'verifyCode':$('#verifyCode').val(),
                'type_id':$('#type').val(),
                'room_id':$('#room').val(),
                'loc':$('input[name=loc]').val(),
            },
            dataType:'json',
            success:function (data) {
                if(data.status == 1){
                    top.layer.close(index);
                    top.layer.msg("设备添加成功！");
                    layer.closeAll("iframe");
                    //刷新父页面
                    parent.location.reload();
                }else{
                    top.layer.close(index);
                    top.layer.msg("设备添加失败！");
                }
            }
        })
        return false;
    });
})
